<template>
	<div class="upload-box">
		<el-upload
			ref="uploadEl"
			action="#"
			:id="uuid"
			:class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
			:multiple="false"
			:disabled="self_disabled"
			:show-file-list="false"
			:http-request="handleHttpUpload"
			:before-upload="beforeUpload"
			:on-success="uploadSuccess"
			:on-error="uploadError"
			:drag="drag"
			:accept="fileType.join(',')"
			:auto-upload="false"
			:on-change="changeFile"
			:headers="headers"
		>
			<template v-if="fileUrl">
				{{ fileUrl }}
				<div class="upload-handle" @click.stop>
					<div class="handle-icon" @click="selectingFile" v-if="!self_disabled">
						<span class="iconfont iconedit-3 pb-1" />
						<span>重新上传</span>
					</div>
					<div class="handle-icon" @click="deleteFile" v-if="!self_disabled">
						<span class="iconfont icontrash-2 pb-1" />
						<span>删除文件</span>
					</div>
				</div>
			</template>
			<template v-else>
				<div class="upload-empty">
					<div>
						<i class="iconfont" :class="props.uploadIcon" style="font-size: 35px" />
					</div>
					<div>{{ props.emptyTips }}</div>
				</div>
			</template>
		</el-upload>
		<div class="el-upload__tip">
			<slot name="tip"></slot>
		</div>
	</div>
</template>

<script setup lang="ts" name="UploadImg">
import { ref, computed, inject } from "vue";
import { uploadImg } from "@/api/modules/upload";
import { generateUUID } from "@/utils/util";
import { ElNotification, formContextKey, formItemContextKey } from "element-plus";
import type { UploadProps, UploadRequestOptions } from "element-plus";
import { showTips } from "../../utils/util";
import { dayjs } from "element-plus";

interface UploadFileProps {
	headers?: any;
	emptyTips?: string;
	uploadIcon?: string;
	fileUrl?: string;
	showTips?: boolean;
	api?: (params: any) => Promise<any>; // 上传的 api 方法，一般项目上传都是同一个 api 方法，在组件里直接引入即可 ==> 非必传
	drag?: boolean; // 是否支持拖拽上传 ==> 非必传（默认为 true）
	disabled?: boolean; // 是否禁用上传组件 ==> 非必传（默认为 false）
	fileSize?: number; // 大小限制 ==> 非必传（默认为 5M）
	fileType?: string[]; // 类型限制 ==> 非必传（默认为 ["image/jpeg", "image/png", "image/gif"]）
	height?: string; // 组件高度 ==> 非必传（默认为 150px）
	width?: string; // 组件宽度 ==> 非必传（默认为 150px）
	borderRadius?: string; // 组件边框圆角 ==> 非必传（默认为 8px）
	params?: any;
}

// 接受父组件参数
const props = withDefaults(defineProps<UploadFileProps>(), {
	emptyTips: "请选择上传的文件",
	uploadIcon: "iconbx-upload",
	fileUrl: "",
	drag: true,
	showTips: true,
	disabled: false,
	fileSize: 500,
	fileType: () => [],
	height: "150px",
	width: "150px",
	borderRadius: "8px",
	params: {}
});

// 生成组件唯一id
const uuid = ref("id-" + generateUUID());

// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
	return props.disabled || formContext?.disabled;
});

/**
 * @description 上传
 * @param options 上传的文件
 * */
interface UploadEmits {
	(e: "update:fileUrl", value: string): void;
	(e: "check-validate"): void;
	(e: "submit", value: Promise<any>): void;
	(e: "submitFileInfo", value: Promise<any>): void;
}
const changeFile = () => {
	uploadEl.value.submit();
};
const handleHttpUpload = async (options: UploadRequestOptions) => {
	let formData = new FormData();
	for (let key in formParam.data) {
		formData.append(key, formParam.data[key]);
	}
	for (let key in props.params) {
		formData.append(key, props.params[key]);
	}
	formData.append("file", options.file);
	formData.append("size", options.file.size + "");
	formData.append("type", options.file.type);
	try {
		const api = props.api ?? uploadImg;
		const res = await api(formData);
		props.showTips && showTips(res.code, "上传文件", res.message);
		emit("update:fileUrl", res.result);
		// 调用 el-form 内部的校验方法（可自动校验）
		formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
		emit("check-validate");
		res.result = {
			url: res.result,
			name: options.file.name,
			updateTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
			size: options.file.size,
			type: options.file.type
		};
		emit("submitFileInfo", res);
	} catch (error) {
		options.onError(error as any);
	}
};

/**
 * @description 删除
 * */
const deleteFile = () => {
	emit("update:fileUrl", "");
};

/**
 * @description 选择文件
 * */
const selectingFile = () => {
	const dom = document.querySelector(`#${uuid.value} .el-upload__input`);
	dom && dom.dispatchEvent(new MouseEvent("click"));
	// uploadEl.value.handleStart();
};
/**
 * @description 文件上传之前判断
 * @param rawFile 上传的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
	//返回true，执行上传，否则终止
	if (!rawFile.size) {
		ElNotification({
			title: "温馨提示",
			message: "文件内容为空，请您重新上传！",
			type: "error"
		});
		return false;
	} else {
		return true;
	}
};

// 上传成功提示
const uploadSuccess = (res: any, file: any) => {
	console.log(res, file);
	// ElNotification({
	// 	title: "温馨提示",
	// 	message: "上传成功！",
	// 	type: "success"
	// });
};

// 上传错误提示
const uploadError = () => {
	ElNotification({
		title: "温馨提示",
		message: "上传失败，请您重新上传！",
		type: "error"
	});
};
const emit = defineEmits<UploadEmits>();
const uploadEl = ref();
const formParam = reactive<any>({
	data: {}
});

defineExpose({ selectingFile });
</script>
<style scoped lang="scss">
.is-error {
	.upload {
		:deep(.el-upload),
		:deep(.el-upload-dragger) {
			border: 1px dashed var(--el-color-danger) !important;
			&:hover {
				border-color: var(--el-color-primary) !important;
			}
		}
	}
}
:deep(.disabled) {
	.el-upload,
	.el-upload-dragger {
		cursor: not-allowed !important;
		background: var(--el-disabled-bg-color);
		border: 1px dashed var(--el-border-color-darker) !important;
		&:hover {
			border: 1px dashed var(--el-border-color-darker) !important;
		}
	}
}
.upload-box {
	.no-border {
		:deep(.el-upload) {
			border: none !important;
		}
	}
	:deep(.upload) {
		.el-upload {
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			width: v-bind(width);
			height: v-bind(height);
			overflow: hidden;
			border: 1px dashed var(--el-border-color-darker);
			border-radius: v-bind(borderRadius);
			transition: var(--el-transition-duration-fast);
			&:hover {
				border-color: var(--el-color-primary);
				.upload-handle {
					opacity: 1;
				}
			}
			.el-upload-dragger {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 100%;
				padding: 0;
				overflow: hidden;
				background-color: transparent;
				border: 1px dashed var(--el-border-color-darker);
				border-radius: v-bind(borderRadius);
				&:hover {
					border: 1px dashed var(--el-color-primary);
				}
			}
			.el-upload-dragger.is-dragover {
				background-color: var(--el-color-primary-light-9);
				border: 2px dashed var(--el-color-primary) !important;
			}
			.upload-image {
				width: 100%;
				height: 100%;
				object-fit: contain;
			}
			.upload-empty {
				position: relative;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 12px;
				line-height: 30px;
				color: var(--el-color-info);
				.el-icon {
					font-size: 28px;
					color: var(--el-text-color-secondary);
				}
			}
			.upload-handle {
				position: absolute;
				top: 0;
				right: 0;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100%;
				height: 100%;
				cursor: pointer;
				background: rgb(0 0 0 / 60%);
				opacity: 0;
				transition: var(--el-transition-duration-fast);
				.handle-icon {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 0 6%;
					color: aliceblue;
					.iconfont {
						margin-bottom: 10px;
						font-size: 20px;
					}
					span {
						font-size: 85%;
						line-height: 85%;
					}
				}
			}
		}
	}
	.el-upload__tip {
		line-height: 18px;
		text-align: center;
	}
}
</style>
